<template>
  <div class="mh-container">
    <div
      class="mh-scene"
      :style="{
        transform: `translate(${position.x}px, ${position.y}px)`,
      }"
      @click="sceneClick"
    ></div>
    <div
      class="mh-role"
      ref="role"
      :style="{
        transform: `rotateY(${direction === 'r' ? '180deg' : '0deg'})`,
      }"
    ></div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
const role = ref(null)
const direction = ref('')
const position = reactive({
  x: 0,
  y: 0,
})
// 获取视图尺寸
const getViewportDimensions = () => {
  return {
    width: document.querySelector('.mh-container')?.offsetWidth || 800,
    height: document.querySelector('.mh-container')?.offsetHeight || 500,
  }
}
// 边界检测
const checkBoundaries = (x, y) => {
  // 场景尺寸
  const sceneWidth = document.querySelector('.mh-scene')?.offsetWidth
  const sceneHeight = document.querySelector('.mh-scene')?.offsetHeight
  const viewport = getViewportDimensions()
  let status = '正常'

  // 计算最大可移动范围（负值）
  const maxX = -(sceneWidth - viewport.width)
  const maxY = -(sceneHeight - viewport.height)

  // 限制在边界内
  const newX = Math.min(Math.max(x, maxX), 0)
  const newY = Math.min(Math.max(y, maxY), 0)

  // 设置边界状态
  if (newX !== x || newY !== y) {
    status = '已到达边界'
  }

  return { x: newX, y: newY, status }
}
const sceneClick = (e) => {
  const { pageX, pageY } = e
  console.log('1', pageX, pageY)
  // const { left, top } = role.value.getBoundingClientRect()
  const viewport = getViewportDimensions()

  console.log('111', viewport.width / 2, pageX - viewport.width / 2)
  direction.value = pageX - viewport.width / 2 > 0 ? 'r' : 'l'
  console.log('direction', direction.value)
  const _x = position.x - (pageX - viewport.width / 2)
  const _y = position.y - (pageY - viewport.height / 2)
  const boundedPos = checkBoundaries(_x, _y)
  position.x = boundedPos.x
  position.y = boundedPos.y
  // position.y=pageY>top?top-pageY:pageX-top;
}
</script>
<style lang="css" scoped>
.mh-container {
  width: 100vw;
  height: 100vh;
  box-sizing: border-box;
  position: relative;
  /* overflow: hidden; */
}
.mh-scene {
  width: 4000px;
  height: 2000px;
  background: url(../assets/scene_s.jpg) no-repeat center/100%;
  position: absolute;
  left: 0;
  top: 0;
  transition: all 0.5s;
}
.mh-role {
  width: 60px;
  height: 60px;
  border-radius: 60px;
  background: url(../assets/LTZ.png) no-repeat center/100%;
  position: absolute;
  left: 50%;
  top: 50%;
  /* box-shadow: 0 0 20px red; */
}
</style>
